package com.letoken.platform.admin.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.letoken.platform.admin.service.AdminUserService;
import com.letoken.platform.pub.annotation.auth.NotAuthorization;
import com.letoken.platform.pub.annotation.auth.Permission;
import com.letoken.platform.pub.annotation.pub.Trim;
import com.letoken.platform.pub.req.PageData;
import com.letoken.platform.pub.res.ApiResponse;
import com.letoken.platform.pub.util.RequestUtil;
import com.letoken.platform.repo.admin.req.user.*;
import com.letoken.platform.repo.admin.res.system.UserCommunityKolRes;
import com.letoken.platform.repo.admin.res.user.AdminUserRes;
import com.letoken.platform.repo.admin.res.user.QueryAdminAccountByIdRes;
import com.letoken.platform.repo.admin.res.user.QueryAdminAccountRes;
import com.letoken.platform.repo.admin.res.user.QueryRoleTypeRes;
import com.letoken.platform.repo.app.dao.*;
import com.letoken.platform.repo.app.po.AppRankingDetail;
import com.letoken.platform.repo.app.po.AppUserTeam;
import com.letoken.platform.repo.app.po.AppUserTeamPath;
import com.letoken.platform.repo.mall.dao.AppMallIssueRecordMapper;
import com.letoken.platform.repo.utlis.PageDataUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author letokenlabs
 * @date 2022/11/11
 */
@RestController
@RequestMapping("/user")
@Api(tags = "admin用户相关接口")
public class AdminUserController {

    @Resource
    private AdminUserService adminUserService;

    @Autowired
    private HttpServletRequest request;

    @Resource
    private AppUserTeamMapper appUserTeamMapper;

    @Resource
    private AppUserAssetsHistoryMapper appUserAssetsHistoryMapper;

    @Resource
    private AppUserTeamPathMapper appUserTeamPathMapper;

    @Resource
    private AppFundV2DetailMapper appFundV2DetailMapper;

    @Resource
    private AppUserIssueRecordMapper appUserIssueRecordMapper;

    @Resource
    private AppMallIssueRecordMapper appMallIssueRecordMapper;


    @Trim
    @NotAuthorization
    @PostMapping("/login")
    @ApiOperation(value = "admin用户登录", notes = "admin用户登录")
    public ApiResponse<AdminUserRes> login(@RequestBody @Validated AdminUserReq req) {
        return ApiResponse.create(adminUserService.login(req, RequestUtil.getIpAddr(request)));
    }

    //    @PostMapping("/getUserInfo")
//    @ApiOperation(value = "admin用户信息", notes = "admin用户信息")
//    public ApiResponse<AdminUserInfoRes> getUserInfo() {
//        return ApiResponse.create(adminUserService.getUserInfo());
//    }
    @Permission(uri = "/user/query", qx = "/admin/accountList")
    @Trim
    @PostMapping("/query")
    @ApiOperation(value = "查询管理账号列表", notes = "查询管理账号列表")
    public ApiResponse<PageData<QueryAdminAccountRes>> queryAdminAccount(@RequestBody @Validated QueryAdminAccountReq req) {
        return ApiResponse.create(adminUserService.queryAdminAccount(req));
    }

    @Permission(uri = "/user/query", qx = "/user/query")
    @Trim
    @PostMapping("/query/{adminUserId}")
    @ApiOperation(value = "根据id查询管理账号", notes = "根据id查询管理账号")
    public ApiResponse<QueryAdminAccountByIdRes> queryAdminAccountById(@PathVariable("adminUserId") Integer adminUserId) {
        return ApiResponse.create(adminUserService.queryAdminAccountById(adminUserId));
    }

    @Permission(uri = "/user/add", qx = "/user/add")
    @Trim
    @PostMapping("/add")
    @ApiOperation(value = "新增管理账户", notes = "新增管理账户")
    public ApiResponse addAccountManagement(@RequestBody @Validated AddAdminAccountReq adminAccountReq) {
        adminUserService.addAccountManagement(adminAccountReq);
        return ApiResponse.create();
    }

    @Permission(uri = "/user/update", qx = "/user/update")
    @Trim
    @PostMapping("/update")
    @ApiOperation(value = "修改管理账户", notes = "修改管理账户")
    public ApiResponse UpdateAccountManagement(@RequestBody @Validated UpdateAdminAccountReq req) {
        adminUserService.UpdateAccountManagement(req);
        return ApiResponse.create();
    }

    @Permission(uri = "/user/delete", qx = "/user/delete")
    @Trim
    @PostMapping("/delete/{adminUserId}")
    @ApiOperation(value = "删除管理账户", notes = "删除管理账户")
    public ApiResponse deleteAccountManagement(@PathVariable("adminUserId") Integer adminUserId) {
        adminUserService.deleteAccountManagement(adminUserId);
        return ApiResponse.create();
    }

    @Permission(uri = "/user/enable", qx = "/user/enable")
    @Trim
    @PostMapping("/enable/{adminUserId}")
    @ApiOperation(value = "启用管理账户 0正常 1异常", notes = "启用管理账户 0正常 1异常")
    public ApiResponse EnableAccountManagement(@PathVariable("adminUserId") Integer adminUserId) {
        adminUserService.EnableAccountManagement(adminUserId);
        return ApiResponse.create();
    }

    @Permission(uri = "/user/disable", qx = "/user/disable")
    @Trim
    @PostMapping("/disable/{adminUserId}")
    @ApiOperation(value = "禁用管理账户 0正常 1异常", notes = "禁用启用管理账户 0正常 1异常")
    public ApiResponse disableAccountManagement(@RequestBody @PathVariable("adminUserId") Integer adminUserId) {
        adminUserService.disableAccountManagement(adminUserId);
        return ApiResponse.create();
    }

//
//    @PostMapping("/editListLocked")
//    @ApiOperation(value = "批量停用", notes = "批量停用")
//    public ApiResponse<FlagStatusRes> updateListLocked(@RequestBody @Validated UpdateAdminLockedListReq req) {
//        return ApiResponse.create(adminUserService.listUpdateLocked(req));
//    }
//
//    @PostMapping("/editListLockedOff")
//    @ApiOperation(value = "批量启用", notes = "批量启用")
//    public ApiResponse<FlagStatusRes> updateListLockedOff(@RequestBody @Validated UpdateAdminLockedListReq req) {
//        return ApiResponse.create(adminUserService.listUpdateLockedOff(req));
//    }
//
//    @PostMapping("/queryById")
//    @ApiOperation(value = "用户详情返回（编辑）", notes = "用户详情返回（编辑）")
//    public ApiResponse<QueryAdminAccountRes> queryById(@RequestBody @Validated QueryAdminAccountByIdReq queryAdminAccountByIdReq) {
//        return ApiResponse.create(adminUserService.queryAdminAccountById(queryAdminAccountByIdReq));
//    }
//
//    @PostMapping("/updateAdminAccount")
//    @ApiOperation(value = "更新管理账号信息", notes = "更新管理账号信息")
//    public ApiResponse<FlagStatusRes> updateAdminAccount(@RequestBody @Validated UpdateAdminAccountReq updateAdminAccountReq) {
//        return ApiResponse.create(adminUserService.updateAdminAccount(updateAdminAccountReq));
//    }

    @Permission(uri = "/user/community/kol/list", qx = "/user/community/kol/list")
    @Trim
    @PostMapping("/community/kol/list")
    @ApiOperation(value = "禁用管理账户 0正常 1异常", notes = "禁用启用管理账户 0正常 1异常")
    public ApiResponse communityKolList(@RequestBody UserCommunityKolListReq req) {
        Page<UserCommunityKolRes> page = appUserTeamMapper.page(new Page<>(req.getPageReq().getPage(), req.getPageReq().getSize()), req.getUserId(), req.getLevel());

        /*Set<Integer> communityLeaderUserIds = appUserTeamMapper.listInt();

        for (UserCommunityKolRes record : page.getRecords()) {
            List<AppUserTeamPath> appUserTeamPaths = appUserTeamPathMapper.listByInviteId(record.getUserId());
            List<Integer> inviteeIds = new ArrayList<>();
            for (AppUserTeamPath appUserTeamPath : appUserTeamPaths) {
                if (communityLeaderUserIds.contains(appUserTeamPath.getUserId())) {
                    continue;
                }
                if (StringUtils.hasLength(appUserTeamPath.getInvitePath())) {
                    String[] superiorUserIds = appUserTeamPath.getInvitePath().split(",");
                    for (String superiorUserId : superiorUserIds) {
                        Integer intSuperiorUserId = Integer.valueOf(superiorUserId);
                        if (communityLeaderUserIds.contains(intSuperiorUserId)) {
                            if (intSuperiorUserId.equals(record.getUserId())) {
                                inviteeIds.add(appUserTeamPath.getUserId());
                            } else {
                                break;
                            }
                        }
                    }
                }
            }
            if (!CollectionUtils.isEmpty(inviteeIds)) {

                BigDecimal teamFundAchievement = appUserAssetsHistoryMapper.sumAmountByTypeAndUserIdsAndDate(19, inviteeIds, null, null);
                if(teamFundAchievement.compareTo(BigDecimal.ZERO) < 0){
                    teamFundAchievement = teamFundAchievement.negate();
                }
                record.setTeamfundAchievement(teamFundAchievement);

                BigDecimal teamSumValue = appUserAssetsHistoryMapper.sumAmountByTypeAndUserIdsAndDate(3, inviteeIds, null, null);
                if(teamSumValue.compareTo(BigDecimal.ZERO) < 0){
                    teamSumValue = teamSumValue.negate();
                }
                record.setTeamSumValue(teamSumValue);

                BigDecimal teamMallAchievement = appUserIssueRecordMapper.sumIssueAmountByUserIds(inviteeIds);
                if(teamMallAchievement.compareTo(BigDecimal.ZERO) < 0){
                    teamMallAchievement = teamMallAchievement.negate();
                }
                record.setTeamMallAchievement(teamMallAchievement);

                LocalDate yesterday = LocalDate.now().minusDays(1);

                LocalDateTime yesterdayMin =  LocalDateTime.of(yesterday, LocalTime.MIN);

                LocalDateTime yesterdayMax =  LocalDateTime.of(yesterday, LocalTime.MAX);

                BigDecimal yesterdayTeamFund = appUserAssetsHistoryMapper.sumAmountByTypeAndUserIdsAndDate(19, inviteeIds, yesterdayMin, yesterdayMax);
                if(yesterdayTeamFund.compareTo(BigDecimal.ZERO) < 0){
                    yesterdayTeamFund = yesterdayTeamFund.negate();
                }
                record.setYesterdayTeamFund(yesterdayTeamFund);

                BigDecimal yesterdayTeamCoinage = appUserAssetsHistoryMapper.sumAmountByTypeAndUserIdsAndDate(3, inviteeIds, yesterdayMin, yesterdayMax);
                if(yesterdayTeamCoinage.compareTo(BigDecimal.ZERO) < 0){
                    yesterdayTeamCoinage = yesterdayTeamCoinage.negate();
                }
                record.setYesterdayTeamCoinage(yesterdayTeamCoinage);


                BigDecimal yesterdayTeamConsumption = appUserIssueRecordMapper.sumIssueAmountByUserIdsAndDate(inviteeIds, yesterdayMin, yesterdayMax);
                if(yesterdayTeamConsumption.compareTo(BigDecimal.ZERO) < 0){
                    yesterdayTeamConsumption = yesterdayTeamConsumption.negate();
                }
                record.setYesterdayTeamConsumption(yesterdayTeamConsumption);
            }
            record.setTeamMember(inviteeIds.size());
        }*/
        return ApiResponse.create(PageDataUtil.getPageData(page));
    }

}
